<?php
/*
 * Nekakšna DAO skripta, samo funkcije za povezavo z bazo
 */
function dbCleanParameter($param){  //Funkcija očisti parameter proti SQL injectionu in XSSdju
    return strip_tags(mysql_escape_string($param));
}
function dbGetResult($query){ //funkcija, ki se poveze z bazo in vrne rezultat glede na string poizvedbe.
        //PODATKI ZA BAZO
        $usrname="root";
        $pass="1234";
        $url="localhost";
        $schema="PodutikRecordsDB";
        
	if ( !( $database = mysql_connect( $url,$usrname, $pass ) ) )                      
		die( "Could not connect to database </body></html>" );
	   
	// open database
	if ( !mysql_select_db( $schema, $database ) )
		die( "Could not open database </body></html>" );

        //$query = mysql_real_escape_string(strip_tags($query)); //Preprečuje XSS in SQL injection
	// query Products database
	if ( !( $result = mysql_query( $query, $database ) ) ) {
		print( "<p>Could not execute query!</p>" );
		die( mysql_error() . "</body></html>" );
	 } // end if

	 mysql_close( $database );
	 return $result;
}

//funkcija, ki naredi string za poizvedbo v bazi.
function createArtikelQuery(){	
	$query = "SELECT * FROM Artikel WHERE zaloga > 0 AND Aktiviran = 1"; //privzeto je to poizvedba (�e so vnosna polja prazna)
	$bool = false;
	$bool1 = false;
        
	if (isset($_POST["sort-by"]) and isset($_POST["search"])){          
		$sort_by = dbCleanParameter($_POST["sort-by"]);
		$search = dbCleanParameter($_POST["search"]);					
	}
			
	if (isset($sort_by) and isset($search) and $sort_by != "" and $search != "") {
		// build SELECT query
		$bool = true;
		$query = "SELECT * FROM Artikel WHERE zaloga > 0 AND Aktiviran = 1 AND $sort_by LIKE '%$search%'";
	}
	
	if (isset($_GET["type"]) and dbCleanParameter ($_GET["type"]) != "everything"){
		$type = dbCleanParameter($_GET["type"]);
                $query .= " AND zvrst = '$type'";
	} else{
                $query .= " AND top = '1'";
	}
	
	if (isset($_POST["show-only"])){
		$media = dbCleanParameter($_POST["show-only"]);
		if (is_numeric(substr($media, 0, 2))){
			if (strlen($media) < 3 ) {
				//if($bool or $bool1)
					$query .= " AND cena >= $media";
				//else
					//$query .= " WHERE cena >= $media";
			}
			else{
				$media1 = substr($media, 0, 2);
				$media2 = substr($media,3,2);
				//if($bool or $bool1)
					$query .= " AND cena BETWEEN $media1 AND $media2";
				//else
					//$query .= " WHERE cena BETWEEN $media1 AND $media2";
			}
		}				
		else if ($media != "ever")
			//if($bool or $bool1)
				$query .= " AND media = '$media'";
			//else
				//$query .= " WHERE media = '$media'";
	}

	if (isset($_POST["sort-by1"])){
		$order_by = dbCleanParameter($_POST["sort-by1"]);
		$query .= " ORDER BY $order_by";
	}
	
	if (!strpos($query,'ORDER BY')) {
		$query .= " ORDER BY izvajalec";
	}
	return $query;
}
?>
